import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCartStore = defineStore('cart', () => {


    const cartList = ref([])
    // const checkBoxs = ref()
    const addCartList = (data) => {

        //传过来的数据，在购物车中(cartList)查看是否有这一项
        const r = cartList.value.find(item => item.skuId === data.skuId)
        if (r) {
            r.count += data.count
        } else {
            cartList.value.push(data)
        }
    }
    const delCart = (skuId) => {
        //1.找到要删除的下标值 splice
        //2.使用数组的过滤方法  filter
        // const index = cartList.value.findIndex(item => item.skuId = skuId)
        // cartList.value.splice(index, 1)
        cartList.value = cartList.value.filter(item => item.skuId != skuId)
    }
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

    ///单选按钮实现
    const singleCheck = (selected, skuId) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
        // if (cartList.value.findIndex(item => item.selected = true)) {
        //     checkBoxs.value = false
        // } else {
        //     checkBoxs.value = true
        // }
        // if (!a()) {
        //     checkBoxs.value = true
        // } else {
        //     checkBoxs.value = false
        // }
    }
    //全选按钮实现
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
        // checkBoxs.value = selected
    }
    //是否全选
    const isAll = computed(() => cartList.value.every(item => item.selected))
    // const a = () => {
    //     return cartList.value.find(item => item.selected === false)

    // }
    //已选中的总数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    //已选中的总价格
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

    return {
        cartList,
        addCartList,
        delCart,
        allCount,
        allPrice,
        singleCheck,
        allCheck,
        isAll,
        selectedCount,
        selectedPrice
    }
}, { persist: true }
)